using System;
using System.Collections.Generic;
using System.Text;
using Rapier.Kodachi.Shared;
using System.IO;
using System.Drawing;

namespace Rapier.Kodachi.Core.Actions
{
    public class PrependTo : Action
    {
        #region Constructor
        public PrependTo(Plugin plugin) 
            : base(plugin, "Rapier.CorePlugin.PrependTo", "Prepend to...", "Prepends Direct Item to Indirect Item (Text File).")
        {
            IndirectItemUse = IndirectItemUse.Required;
            string itemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
            GetImage = delegate() { return CoreCatalog.GetImageFromPath(itemPath); };
        }
        #endregion

        #region Action Members
        public override bool IsValidDirect(Item directItem)
        {
            return directItem.Properties.ContainsKey("Text");
        }

        public override bool IsValidIndirect(Item indirectItem)
        {
            return indirectItem.Properties.ContainsKey("Path") && CorePlugin.IsTextFile(indirectItem);
        }

        public override void Execute(Item[] directItems, Item[] indirectItems)
        {
            foreach (Item directItem in directItems)
            {
               foreach( Item indirectItem in indirectItems )
               {
                  string fileText = String.Empty;
                  using( StreamReader reader = new StreamReader( indirectItem.Properties["Path"].ToString() ) )
                  {
                     fileText = reader.ReadToEnd();
                  }

                  fileText = directItem.Properties["Text"].ToString() + Environment.NewLine + fileText;
                  using( StreamWriter writer = new StreamWriter( indirectItem.Properties["Path"].ToString(), false ) )
                  {
                     writer.WriteLine( fileText );
                  }
               }
            }
        }
        #endregion
    }
}
